package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserRegisterService;
import com.cskaoyan.user.utils.VerifyRegisterDataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author:ZhouXin
 * @Date:2022/10/25 21:07
 * @Description:
 **/
@RestController
@RequestMapping("/user")
public class RegisterController {


    @Autowired
    IUserRegisterService iUserRegisterService;

    @Autowired
    IKaptchaService iKaptchaService;

    @PostMapping("/register")
    public ResponseData register(@RequestBody Map<String,String> map,HttpServletRequest request){
        //请求体中获取参数
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        //验证验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        try {
            iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseUtil<>().setErrorMsg(e.getMessage());
        }
        //向用户表中插入记录
        UserRegisterRequest registerRequest = new UserRegisterRequest();
        registerRequest.setEmail(email);
        registerRequest.setCaptcha(captcha);
        registerRequest.setUserName(userName);
        registerRequest.setUserPwd(userPwd);

        //对数据进行校验
        try {
            VerifyRegisterDataUtils.verifyRegisterData(registerRequest);
            iUserRegisterService.register(registerRequest);

            return new ResponseUtil<>().setData(null);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseUtil<>().setErrorMsg(e.getMessage());
        }

    }

    @GetMapping("verify")
    public ResponseData userVerify(String uid,String username){
        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUuid(uid);
        userVerifyRequest.setUsername(username);
        iUserRegisterService.verify(userVerifyRequest);
        return new ResponseUtil<>().setData(null);
    }

}
